from public.message import send_qq_text_msg, web_verification_msg
from webpage.webClient import get_web_client
from webpage.mei.urls import register_url, register_get, register_post
from webpage.comm.login import verification_code, try_login, try_logout
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
import random
import re


@web_verification_msg.on_receive
def web_verification(qq: str, code: str):
    verification_code[qq] = code
    return True


@register_get('login')
def login_get(request):
    if m := re.search(r'\?qq=(\d+)&code=(\d{4})', request.GET.get('next', '')):
        qq = m.group(1)
        code = m.group(2)
        if try_login(request, qq, code):
            return redirect(request.GET.get('next', 'index.html'))
    return render(request, 'login.html')


@register_post('login')
def login_post(request):
    qq = request.POST.get('qq')
    code = request.POST.get('code')
    if try_login(request, qq, code):
        return JsonResponse({'success': True})
    else:
        return JsonResponse({'success': False, 'error': '验证码错误'})


@register_post('send_verification')
def send_verification(request):
    qq = request.POST.get('qq')
    if qq:
        code = str(random.randint(1000, 9999))
        verification_code[qq] = code
        ret = get_web_client().send(send_qq_text_msg.build(
            user_id=int(qq),
            text=f'您正在登陆小魅网页版，您的验证码为：{code}，如非本人操作，请勿泄漏此验证码。',
        ))
        if ret:
            return JsonResponse({'success': True})
        else:
            return JsonResponse({'success': False, 'error': '发送验证码失败，请检查小魅是否为您的好友'})
    return JsonResponse({'success': False, 'error': 'QQ号为空'})


@register_url('logout')
@login_required
def logout_view(request):
    qq = request.user.username
    try_logout(request, qq)
    return redirect('login')
